package org.dashboard.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class NameCastTools {
    private static final Logger logger = LoggerFactory.getLogger(NameCastTools.class);

    public static List<Map<String, Object>> listToListMap(List<?> objects) {
        if (objects != null)
            return objects.stream().map(NameCastTools::objectToMap).collect(Collectors.toList());
        return new ArrayList<>();
    }

    public static <T> Map<String, Object> objectToMap(T obj) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (obj != null) {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
                    String propertyName = propertyDesc.getName();
                    Object value = propertyDesc.getReadMethod().invoke(obj);
                    map.put(camelCaseToUnderscore(propertyName), value);
                }
            }
        } catch (Exception e) {
            logger.error("objectToMap", e);
        }
        return map;
    }

    private static String camelCaseToUnderscore(String str) {
        return str.replaceAll("([A-Z]+)", "\\_$1").toLowerCase();
    }

}
